<?php

require_once('json.inc.php');

$page = $_GET['page']; // get the requested page 
$limit = $_GET['rows']; // get how many rows we want to have into the grid 
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort 
$sord = $_GET['sord']; // get the direction 

require('../dbconnect.inc.php');

$rs = $dbh->query('select count(*) from network_map');

if ($rec = $rs->fetchAll(PDO::FETCH_COLUMN, 0))
{
	$count = $rec[0];
}
else
{
	$count = 0;
}

if( $count > 0 ) 
{ 
	$total_pages = ceil($count/$limit); 
} 
else 
{ 
	$total_pages = 0; 
} 

if ($page > $total_pages) 
	$page=$total_pages;


$start = $limit * $page - $limit;

if ($start < 0) 
	$start = 0;

$order_by_cause = 'order by ';

$idx_array = array('c_id' => 'nm.c_id', 'g_name' => 'gr.name', 'c_location' => 'nm.location');

$idx = $idx_array[$sidx];

if (isset($idx) && (($sord == 'asc') || ($sord == 'desc')))
{                     
	$order_by_cause .= $idx . ' ' . $sord;
}
else
{
	$order_by_cause = '';
}


$sth = $dbh->prepare('SELECT nm.c_id, gr.name as g_name, nm.location, nm.next_enc_key ' .  
					 'FROM network_map nm, groups gr ' .  
					 'WHERE gr.g_id = nm.g_id ' . $order_by_cause . ' limit :start,:limit');

$sth->bindParam(':start', intval($start), PDO::PARAM_INT);
$sth->bindParam(':limit', intval($limit), PDO::PARAM_INT);

$sth->execute();

$responce->page = $page; 
$responce->total = $total_pages; 
$responce->records = $count; 

$alldb = $sth->fetchAll(PDO::FETCH_ASSOC);

foreach( $alldb as $key => $val)
{
	$responce->rows[$key]['id'] = $val['c_id'];
	$responce->rows[$key]['cell'] = array( $val['c_id'], $val['g_name'],$val['location'],$val['next_enc_key']);
}

echo json_encode($responce);

?>
